<!-- 开处方页面 -->
<template>
  <div class="prescribing-container">
    <el-row :gutter="10" class="main-container">
      <!-- 左侧面板 - 患者信息 -->
      <el-col :span="7" style="height: 100%">
        <div class="left-panel c-card">
          <!-- 患者信息区域 -->
          <div class="info-section">
            <div class="section-header">
              <div class="header-line"></div>
              <span class="header-title">患者信息</span>
              <el-button type="primary" link class="select-btn" @click="openPatientDialog">选择患者</el-button>
            </div>
            
            <el-form ref="patientFormRef" :model="patientForm" :rules="patientRules" label-width="100px" class="info-form">
              <el-form-item label="患者姓名" prop="psn_name">
                <el-input v-model="patientForm.psn_name" placeholder="请输入患者姓名" />
              </el-form-item>
              
              <el-form-item label="身份证号码" prop="mdtrt_cert_no">
                <el-input v-model="patientForm.mdtrt_cert_no" placeholder="请输入身份证号码" @blur="parseIdCard" />
              </el-form-item>
              
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="patientForm.sex" >
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="年龄" prop="age">
                <el-input v-model="patientForm.age" placeholder="请输入年龄">
                  <template #append>岁</template>
                </el-input>
              </el-form-item>
              
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="patientForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 诊疗信息区域 -->
          <div class="info-section">
            <div class="section-header">
              <div class="header-line"></div>
              <span class="header-title">诊疗信息</span>
            </div>
            
            <el-form :model="diagnosisForm" :rules="diagnosisRules" ref="diagnosisFormRef" label-width="100px" class="info-form">
              <el-form-item label="病种类型" prop="CirculationType">
                <el-radio-group v-model="diagnosisForm.CirculationType">
                  <el-radio label="1">普通</el-radio>
                  <el-radio label="3">慢病</el-radio>
                  <el-radio label="2">统筹</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="相关症状" prop="Symptom">
                <el-input
                  v-model="diagnosisForm.Symptom"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入相关症状"
                />
              </el-form-item>
              
              <el-form-item label="诊断信息" prop="diag_code">
                <el-select
                  class="flex1"
                  v-model="diagnosisForm.diag_code"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入诊断信息"
                  :remote-method="remoteMethod"
                  :loading="remoteLoading"
                  @change="selectChange"
                >
                  <el-option
                    v-for="item in diagOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 过往史区域 -->
          <div class="info-section">
            <div class="section-header">
              <div class="header-line"></div>
              <span class="header-title">过往史</span>
            </div>
            
            <el-form :model="historyForm" label-width="140px" class="history-form">
              <el-form-item label="是否用过此药物">
                <el-radio-group v-model="historyForm.IsTake">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="是否有药物过敏史">
                <el-radio-group v-model="historyForm.IsAllergy">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="肝肾功能是否异常">
                <el-radio-group v-model="historyForm.IsLiverRenalFunctionAbnormity">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="有无不良反应">
                <el-radio-group v-model="historyForm.IsUntowardReaction">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-col>
      
      <!-- 右侧面板 - 药品信息 -->
      <el-col :span="17">
        <div class="right-panel c-card">
          <div class="medicine-header">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
              <el-tab-pane label="西药/中成药处方" name="western"></el-tab-pane>
              <el-tab-pane label="中药处方" name="chinese"></el-tab-pane>
            </el-tabs>
            <el-button type="primary" size="small" @click="openDrugDialog" :disabled="medicineList.length >= 5 && prescriptionData.PrescriptionType == 1">
              新增药品
            </el-button>
          </div>
          
          <!-- 药品列表 -->
          <div class="medicine-table">
            <!-- 中药处方 -->
            <el-table :data="medicineList" style="width: 100%" v-if="activeTab === 'chinese'">
              <el-table-column label="序号" type="index" width="60"></el-table-column>
              <el-table-column label="药品名称" prop="ItemName">
                <template #default="{ row }">
                  <el-input v-model="row.ItemName" placeholder="请输入药品名称" />
                </template>
              </el-table-column>
              <el-table-column label="药品数量" prop="DrugNum">
                <template #default="{ row }">
                  <el-input-number v-model="row.DrugNum" :min="0" placeholder="请输入数量" controls-position="right" />
                  <span class="margin-left">g</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button type="danger" size="small" @click="deleteMedicine($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 西药/中成药处方 -->
            <el-table :data="medicineList" style="width: 100%" v-else>
              <el-table-column label="药品名称" prop="ItemName">
                <template #default="{ row }">
                  <el-input v-model="row.ItemName" placeholder="请输入药品名称" />
                </template>
              </el-table-column>
              <el-table-column label="药品数量" prop="DrugNum">
                <template #default="{ row }">
                  <el-input-number v-model="row.DrugNum" :min="0" style="width: 90px;" placeholder="请输入数量" controls-position="right" />
                </template>
              </el-table-column>
              <el-table-column label="规格" width="120">
                <template #default="{ row }">
                  <div>
                    {{ row.spec }}
                    <span>/{{ row.minPackagingQuantity }}</span>
                    <span>{{ row.minPreparationUnt }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="每次用量" width="160">
                <template #default="{ row }">
                  <div class="aic">
                    <el-input type="number" v-model="row.sinDoscnt" placeholder="请输入" />
                    <el-select v-model="row.sinDosunt" placeholder="请选择" class="margin-left-xs" style="width: 100px;">
                      <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="频率">
                <template #default="{ row }">
                  <div class="aic">
                    <el-select v-model="row.used_frqu_dscr" placeholder="请选择">
                      <el-option v-for="item in frequencyOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="用法">
                <template #default="{ row }">
                  <div class="aic">
                    <el-select v-model="row.usageDosage" placeholder="请选择">
                      <el-option v-for="item in administrationOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="可服用天数">
                <template #default="{ row }">
                  <el-input placeholder="请输入" style="width: 80px" v-model="row.prd_days" />天
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ row, $index }">
                  <el-button type="danger" size="small" @click="deleteMedicine($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 中药处方额外表单 -->
            <el-form 
              class="margin-top" 
              :model="chineseMedicineForm" 
              :rules="chineseMedicineRules"
              label-width="80px" 
              ref="chineseMedicineFormRef"
              v-if="activeTab === 'chinese' && medicineList.length > 0">
              <el-form-item label="总剂量" prop="cmDrugNum">
                <el-input v-model="chineseMedicineForm.cmDrugNum" style="width: 120px;" />
              </el-form-item>
              <el-form-item label="用法" prop="cmused_mtd">
                <el-select v-model="chineseMedicineForm.cmused_mtd" placeholder="请选择" style="width: 120px;">
                  <el-option 
                    v-for="item in chineseUsageOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="用药频次" prop="cmused_frqu">
                <el-select v-model="chineseMedicineForm.cmused_frqu" placeholder="请选择" style="width: 120px;">
                  <el-option 
                    v-for="item in frequencyOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 底部操作按钮 -->
          <div class="action-buttons">
            <el-button type="primary" plain @click="previewPrescription">预览</el-button>
            <el-button type="primary" :loading="confirmLoading" @click="confirmPrescription">确认处方</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 选择患者弹窗 -->
    <el-dialog v-model="patientDialogVisible" title="选择患者" width="800px" append-to-body>
      <div class="dialog-search margin-bottom">
        <el-input
          v-model="patientSearch.name"
          placeholder="请输入患者姓名"
          clearable
          style="width: 200px;"
          @keyup.enter="searchPatients"
          class="margin-right"
        />
        <el-input
          v-model="patientSearch.phone"
          placeholder="请输入手机号"
          clearable
          style="width: 200px;"
          @keyup.enter="searchPatients"
          class="margin-right"
        />
        <el-button type="primary" @click="searchPatients">搜索</el-button>
      </div>
      
      <el-table 
        :data="patientList" 
        style="width: 100%" 
        highlight-current-row
        @row-click="selectPatient">
        <el-table-column prop="psn_name" label="患者姓名" width="120"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">{{ row.sex === '1' ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="mdtrt_cert_no" label="身份证号"></el-table-column>
      </el-table>
      
      <el-pagination
        class="margin-top text-right"
        v-model:current-page="patientPagination.pageNo"
        v-model:page-size="patientPagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="patientPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePatientSizeChange"
        @current-change="handlePatientCurrentChange"
      />
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="patientDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectPatient" :disabled="!selectedPatient">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 药品选择弹窗 -->
    <el-dialog 
      v-model="drugDialogVisible" 
      :title="(activeTab === 'chinese' ? '中药' : '西药') + '药品选择'" 
      width="800px" 
      append-to-body>
      <div class="dialog-search margin-bottom">
        <el-input
          v-model="drugSearch.name"
          placeholder="请输入药品名称"
          clearable
          style="width: 200px;"
          @input="handleDrugSearchInput('name')"
          @keyup.enter="searchDrugs"
          class="margin-right"
        />
        <el-input
          v-model="drugSearch.code"
          placeholder="请输入药品编码"
          clearable
          style="width: 200px;"
          @input="handleDrugSearchInput('code')"
          @keyup.enter="searchDrugs"
          class="margin-right"
        />
        <el-button type="primary" @click="searchDrugs">搜索</el-button>
      </div>
      
      <el-table 
        :data="drugList" 
        style="width: 100%" 
        @selection-change="handleDrugSelectionChange"
        ref="drugTableRef">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column 
          v-for="col in drugColumns" 
          :key="col.key" 
          :label="col.name" 
          :prop="col.key">
        </el-table-column>
      </el-table>
      
      <el-pagination
        class="margin-top text-right"
        v-model:current-page="drugPagination.pageNo"
        v-model:page-size="drugPagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="drugPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleDrugSizeChange"
        @current-change="handleDrugCurrentChange"
      />
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drugDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectDrug" :disabled="selectedDrugs.length === 0">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 处方预览弹窗 -->
    <prescriptionDialog 
      ref="prescriptionDialogRef" 
      :orderInfo="prescriptionData" 
      :medicineForm="chineseMedicineForm" 
      :signatures="signatures" 
      :medicineListProps="medicineList">
    </prescriptionDialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import prescriptionDialog from '@/components/prescription-dialog/prescription-dialog.vue'
import { useUserStore } from '@/store/user'

// 引用组件
const prescriptionDialogRef = ref(null)
const patientFormRef = ref(null)
const diagnosisFormRef = ref(null)
const chineseMedicineFormRef = ref(null)
const drugTableRef = ref(null)
const signatures = ref({})
const OnlineInquiryNo = ref('')   // 处方号
const userInfo = useUserStore().userInfo

// 表单数据
const patientForm = reactive({
  psn_name: '',
  sex: '',
  age: '',
  phone: '',
  mdtrt_cert_no: ''
})

const diagnosisForm = reactive({
  Symptom: '',
  diag_code: '',
  diag_name: '',
  CirculationType: '1'
})

const historyForm = reactive({
  IsTake: 1,
  IsAllergy: 0,
  IsLiverRenalFunctionAbnormity: 0,
  IsUntowardReaction: 0
})

// 药品相关数据
const activeTab = ref('western')
const medicineList = ref([])
const confirmLoading = ref(false)

// 中药额外表单
const chineseMedicineForm = reactive({
  cmDrugNum: '',
  cmused_mtd: '',
  cmused_frqu: ''
})

// 患者选择弹窗
const patientDialogVisible = ref(false)
const patientList = ref([])
const selectedPatient = ref(null)
const patientSearch = reactive({
  name: '',
  phone: ''
})

const patientPagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 药品选择弹窗
const drugDialogVisible = ref(false)
const drugList = ref([])
const selectedDrugs = ref([])
const drugSearch = reactive({
  name: '',
  code: ''
})

const drugPagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 药品搜索防抖定时器
const drugSearchDebounceTimer = ref(null)

// 诊断信息相关
const remoteLoading = ref(false)
const diagOptions = ref([])

// 身份证解析状态
const idCardParsed = ref(false)

// 字典选项
const unitOptions = [
  { label: 'mg', value: 'mg' },
  { label: 'g', value: 'g' },
  { label: '片', value: '片' },
  { label: '粒', value: '粒' },
  { label: '支', value: '支' }
]

const frequencyOptions = [
  { label: '每日一次', value: '每日一次' },
  { label: '每日两次', value: '每日两次' },
  { label: '每日三次', value: '每日三次' },
  { label: '每四小时一次', value: '每四小时一次' }
]

const administrationOptions = [
  { label: '口服', value: '口服' },
  { label: '外用', value: '外用' },
  { label: '静脉注射', value: '静脉注射' },
  { label: '肌肉注射', value: '肌肉注射' }
]

const chineseUsageOptions = [
  { label: '水煎服', value: '水煎服' },
  { label: '冲服', value: '冲服' },
  { label: '烊化', value: '烊化' }
]

// 西药字段配置
const wmDrugColumns = [
  { name: '药品代码', key: 'med_list_codg' },
  { name: '注册名称', key: 'reg_nam' },
  { name: '注册剂型', key: 'reg_dosform' },
  { name: '注册规格', key: 'reg_spec' },
  { name: '生产企业', key: 'EnterpriseName' }
]

// 中药字段配置
const cmDrugColumns = [
  { name: '药品名称', key: 'ver_name' },
  { name: '药品编码', key: 'med_list_codg' }
]

const drugColumns = computed(() => {
  return activeTab.value === 'chinese' ? cmDrugColumns : wmDrugColumns
})

// 表单验证规则
const patientRules = {
  psn_name: [{ required: true, message: '请输入患者姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  mdtrt_cert_no: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, 
      message: '请输入正确的身份证号码', trigger: 'blur' }
  ]
}

const diagnosisRules = {
  Symptom: [{ required: true, message: '请输入相关症状', trigger: 'blur' }],
  diag_code: [{ required: true, message: '请选择诊断信息', trigger: 'change' }],
  CirculationType: [{ required: true, message: '请选择病种类型', trigger: 'change' }]
}

const chineseMedicineRules = {
  cmDrugNum: [{ required: true, message: '请输入总剂量', trigger: 'blur' }],
  cmused_mtd: [{ required: true, message: '请选择用法', trigger: 'change' }],
  cmused_frqu: [{ required: true, message: '请选择用药频次', trigger: 'change' }]
}

// 处方数据
const prescriptionData = computed(() => {
  return {
    psn_name: patientForm.psn_name,
    sex: patientForm.sex,
    age: patientForm.age,
    mdtrt_cert_no: patientForm.mdtrt_cert_no,
    phone: patientForm.phone,
    Symptom: diagnosisForm.Symptom,
    diag_name: diagnosisForm.diag_name,
    diag_code: diagnosisForm.diag_code,
    CirculationType: diagnosisForm.CirculationType,
    IsTake: historyForm.IsTake,
    IsAllergy: historyForm.IsAllergy,
    IsLiverRenalFunctionAbnormity: historyForm.IsLiverRenalFunctionAbnormity,
    IsUntowardReaction: historyForm.IsUntowardReaction,
    PrescriptionType: activeTab.value === 'chinese' ? 2 : 1,
    electronicPrescriptionTime: new Date().toISOString().split('T')[0],
    OnlineInquiryNo: OnlineInquiryNo.value
  }
})

// 解析身份证号码
const parseIdCard = () => {
  const idCard = patientForm.mdtrt_cert_no
  if (!idCard) {
    resetIdCardFields()
    return
  }

  // 验证身份证号码格式
  const reg = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!reg.test(idCard)) {
    resetIdCardFields()
    return
  }

  // 解析出生日期
  const birthYear = idCard.substring(6, 10)
  const birthMonth = idCard.substring(10, 12)
  const birthDay = idCard.substring(12, 14)
  const birthDate = new Date(birthYear, birthMonth - 1, birthDay)

  // 计算年龄
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }

  patientForm.age = age.toString()

  // 解析性别 (倒数第二位，奇数为男，偶数为女)
  const genderCode = idCard.substring(16, 17)
  patientForm.sex = parseInt(genderCode) % 2 === 1 ? '1' : '2'

  idCardParsed.value = true
}

// 重置身份证相关信息
const resetIdCardFields = () => {
  patientForm.sex = ''
  patientForm.age = ''
  idCardParsed.value = false
}

// 方法定义
const openPatientDialog = () => {
  patientDialogVisible.value = true
  patientSearch.name = ''
  patientSearch.phone = ''
  patientPagination.pageNo = 1
  getPatientList()
}

const getPatientList = () => {
  const params = {
    pageindex: patientPagination.pageNo - 1,
    pagesize: patientPagination.pageSize,
    ...patientSearch
  }
  
  sa.ajax('/api/pharmacy/patientList', params, function(res) {
    if (res.code === '1') {
      patientList.value = res.data || []
      patientPagination.total = Number(res.totalItems) || 0
    }
  })
}

const searchPatients = () => {
  patientPagination.pageNo = 1
  getPatientList()
}

const handlePatientSizeChange = (val) => {
  patientPagination.pageSize = val
  getPatientList()
}

const handlePatientCurrentChange = (val) => {
  patientPagination.pageNo = val
  getPatientList()
}

const selectPatient = (row) => {
  selectedPatient.value = row
}

const confirmSelectPatient = () => {
  if (!selectedPatient.value) {
    ElMessage.warning('请先选择患者')
    return
  }
  
  // 填充患者信息
  patientForm.psn_name = selectedPatient.value.psn_name
  patientForm.sex = selectedPatient.value.sex
  patientForm.age = selectedPatient.value.age
  patientForm.phone = selectedPatient.value.phone
  patientForm.mdtrt_cert_no = selectedPatient.value.mdtrt_cert_no
  
  // 如果有身份证号，则解析
  if (selectedPatient.value.mdtrt_cert_no) {
    parseIdCard()
  }
   // 清除对应字段的验证状态
  patientFormRef.value.clearValidate(['psn_name', 'sex', 'age', 'phone', 'mdtrt_cert_no'])
  
  patientDialogVisible.value = false
  ElMessage.success('患者信息已填充')
}

const handleTabChange = () => {
  // 切换tab时清空药品列表
  medicineList.value = []
}

const openDrugDialog = () => {
  // 西药做限制
  if (medicineList.value.length >= 5 && prescriptionData.value.PrescriptionType == 1) {
    ElMessage.warning('药品数量已达上限（5个）')
    return
  }
  
  drugDialogVisible.value = true
  drugSearch.name = ''
  drugSearch.code = ''
  drugPagination.pageNo = 1
  selectedDrugs.value = []
  getDrugList()
}

const getDrugList = () => {
  const params = {
    pageindex: drugPagination.pageNo - 1,
    pagesize: drugPagination.pageSize,
    ...drugSearch,
    fixmedins_code: userInfo.fixmedins_code
  }
  
  let platform = import.meta.env.VITE_PLATFORM
  let chineseApiUrl = platform == 'ylyb' ? '/api/CMDPCatalogue/list' : '/api/webPresAdmin/CMDPCatalogueList'
  let westernApiUrl = platform == 'ylyb' ? '/api/WMCPMCatalogue/list' : '/api/webPresAdmin/WMCPMCatalogueList'
  let apiUrl = activeTab.value === 'chinese' ? chineseApiUrl : westernApiUrl
  
  // const apiUrl = activeTab.value === 'chinese' 
  //   ? '/api/webPresAdmin/CMDPCatalogueList' 
  //   : '/api/webPresAdmin/WMCPMCatalogueList'
  sa.ajax(apiUrl, params, function(res) {
    if (res.code === '1') {
      drugList.value = res.data || []
      drugPagination.total = Number(res.totalItems) || 0
    }
  })
}

const searchDrugs = () => {
  // 清除防抖定时器
  if (drugSearchDebounceTimer.value) {
    clearTimeout(drugSearchDebounceTimer.value)
  }
  
  drugPagination.pageNo = 1
  getDrugList()
}

const handleDrugSizeChange = (val) => {
  drugPagination.pageSize = val
  getDrugList()
}

const handleDrugCurrentChange = (val) => {
  drugPagination.pageNo = val
  getDrugList()
}

const handleDrugSelectionChange = (selection) => {
  selectedDrugs.value = selection
}

const confirmSelectDrug = () => {
  if (selectedDrugs.value.length === 0) {
    ElMessage.warning('请先选择药品')
    return
  }
  if(prescriptionData.value.PrescriptionType == 1) {
    if (medicineList.value.length + selectedDrugs.value.length > 5) {
      ElMessage.warning(`最多只能添加5个药品，当前还可添加${5 - medicineList.value.length}个`)
      return
    }
  }
  
  selectedDrugs.value.forEach(drug => {
    const newMedicine = {
      ItemName: activeTab.value === 'chinese' ? drug.ver_name : drug.reg_nam,
      DrugNum: 1,
      ItemCode: drug.med_list_codg,
      MIC_Code: drug.med_list_codg,
      // 西药特有字段
      spec: drug.reg_spec || '',
      minPackagingQuantity: drug.minPackagingQuantity,
      minPreparationUnt: drug.minPreparationUnt,
      sinDoscnt: '',
      sinDosunt: '',
      used_frqu_dscr: '',
      usageDosage: '',
      prd_days: '',
      unt: drug.unt || ''
    }
    
    medicineList.value.push(newMedicine)
  })
  
  drugDialogVisible.value = false
  ElMessage.success(`成功添加${selectedDrugs.value.length}个药品`)
}

const deleteMedicine = (index) => {
  medicineList.value.splice(index, 1)
  ElMessage.success('药品删除成功')
}

// 药品搜索防抖处理
const handleDrugSearchInput = (field) => {
  // 清除之前的定时器
  if (drugSearchDebounceTimer.value) {
    clearTimeout(drugSearchDebounceTimer.value)
  }
  
  // 设置新的防抖定时器（300ms）
  drugSearchDebounceTimer.value = setTimeout(() => {
    drugPagination.pageNo = 1
    getDrugList()
  }, 500)
}

// 获取医师签名
function getSignatures() {
  sa.ajax('/api/webOnlineInquiry/getPresSignatures', {}, function (res) {
    if (res.code === '1') {
      signatures.value = res.data
      // 新增返回一个处方号
      OnlineInquiryNo.value = res.data.presNo
    }
  })
}

// 获取诊断信息列表
const getDiagType = function (name) {
  let params = {
    pageindex: 0,
    pagesize: 100,
    name: name || ''
  }
  sa.ajax('/api/DiagCatalogue/list', params, function (res) {
    if (res.code == '1') {
      remoteLoading.value = false
      diagOptions.value = res.data
    }
  })
}

// 远程搜索诊断信息
function remoteMethod(query) {
  remoteLoading.value = true
  getDiagType(query)
}

// 诊断信息选择后回调
function selectChange(code) {
  const selected = diagOptions.value.find(item => item.code === code)
  if (selected) {
    diagnosisForm.diag_name = selected.name
  }
}

const previewPrescription = () => {
  if (medicineList.value.length === 0) {
    ElMessage.warning('请先添加药品')
    return
  }
  
  // 检查是否填写了诊断信息
  if (!diagnosisForm.diag_code) {
    ElMessage.warning('请填写诊断信息')
    return
  }
  
  prescriptionDialogRef.value?.show(true)
}

// 清空所有表单数据
const resetAllForms = () => {
  // 重置患者信息
  patientForm.psn_name = ''
  patientForm.sex = ''
  patientForm.age = ''
  patientForm.phone = ''
  patientForm.mdtrt_cert_no = ''
  idCardParsed.value = false
  
  // 重置诊断信息
  diagnosisForm.Symptom = ''
  diagnosisForm.diag_code = ''
  diagnosisForm.diag_name = ''
  diagnosisForm.CirculationType = '1'
  
  // 重置过往史
  historyForm.IsTake = 1
  historyForm.IsAllergy = 0
  historyForm.IsLiverRenalFunctionAbnormity = 0
  historyForm.IsUntowardReaction = 0
  
  // 重置药品列表
  medicineList.value = []
  
  // 重置中药额外表单
  chineseMedicineForm.cmDrugNum = ''
  chineseMedicineForm.cmused_mtd = ''
  chineseMedicineForm.cmused_frqu = ''
  
  // 重置tabs
  activeTab.value = 'western'
}

const confirmPrescription = async () => {
  if (medicineList.value.length === 0) {
    ElMessage.warning('请先添加药品')
    return
  }
  
  // 检查是否填写了诊断信息
  if (!diagnosisForm.diag_code) {
    ElMessage.warning('请填写诊断信息')
    return
  }
  
  // 表单验证
  try {
    await patientFormRef.value.validate()
    await diagnosisFormRef.value.validate()
    
    if (activeTab.value === 'chinese' && medicineList.value.length > 0) {
      await chineseMedicineFormRef.value?.validate()
    }
  } catch (error) {
    ElMessage.error('请完善表单信息')
    return
  }
  
  // 验证药品信息
  let valid = true
  for (let i = 0; i < medicineList.value.length; i++) {
    const medicine = medicineList.value[i]
    
    if (!medicine.ItemName) {
      ElMessage.error(`第${i+1}行药品名称不能为空`)
      valid = false
      break
    }
    
    if (!medicine.DrugNum || medicine.DrugNum <= 0) {
      ElMessage.error(`第${i+1}行药品数量必须大于0`)
      valid = false
      break
    }
    
    // 西药验证
    if (activeTab.value !== 'chinese') {
      if (!medicine.sinDoscnt) {
        ElMessage.error(`第${i+1}行每次用量不能为空`)
        valid = false
        break
      }
      
      if (!medicine.sinDosunt) {
        ElMessage.error(`第${i+1}行每次用量单位不能为空`)
        valid = false
        break
      }
      
      if (!medicine.used_frqu_dscr) {
        ElMessage.error(`第${i+1}行频率不能为空`)
        valid = false
        break
      }
      
      if (!medicine.usageDosage) {
        ElMessage.error(`第${i+1}行用法不能为空`)
        valid = false
        break
      }
    }
  }
  
  if (!valid) return
  
  // 中药额外验证
  if (activeTab.value === 'chinese' && medicineList.value.length > 0) {
    if (!chineseMedicineForm.cmDrugNum) {
      ElMessage.error('请输入总剂量')
      return
    }
    
    if (!chineseMedicineForm.cmused_mtd) {
      ElMessage.error('请选择用法')
      return
    }
    
    if (!chineseMedicineForm.cmused_frqu) {
      ElMessage.error('请选择用药频次')
      return
    }
  }
  
  confirmLoading.value = true
  
  try {
    // 显示预览
    prescriptionDialogRef.value?.show(false)
    
    setTimeout(async() => {
      let accessoryId = await prescriptionDialogRef.value?.transPrescription()
      let params = {
        ...patientForm,
        OnlineInquiryItems: medicineList.value,
        ...diagnosisForm,
        ...prescriptionData.value,
        ConsultationMethod: '1', // 图文问诊
        ...historyForm,
        accessoryId,
        presNo: OnlineInquiryNo.value,
        ...chineseMedicineForm,
      }
      
      sa.ajax('/api/webOnlineInquiry/addPresBydoctor', params, function (res) {
        confirmLoading.value = false
        if (res.code == '1') {
          ElMessage.success('处方确认成功')
          // 处方提交成功后清空所有表单
          resetAllForms()
        } else {
          ElMessage.error(res.msg || '处方确认失败')
        }
      })
    }, 300)
  } catch (error) {
    ElMessage.error('处方确认失败')
    confirmLoading.value = false
  }
}

// 页面初始化
onMounted(() => {
  getDiagType()
  getSignatures()
})
</script>

<style scoped lang="scss">
.prescribing-container {
  height: calc(100vh - 84px);
  overflow: hidden;
  padding: 10px;
  .c-card {
    margin: 0;
  }
  .main-container {
    height: 100%;
  }
  
  .left-panel {
    height: 100%;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .info-section {
      .section-header {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        font-size: 16px;
        font-weight: bold;
        
        .header-line {
          width: 4px;
          height: 20px;
          background-color: #409eff;
          margin-right: 10px;
        }
        
        .header-title {
          flex: 1;
        }
      }
      
      .info-form {
        .el-form-item {
          margin-bottom: 18px;
        }
      }
      
      .history-form {
        .radio-group {
          display: flex;
          align-items: center;
          gap: 15px;
        }
      }
    }
  }
  
  .right-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .medicine-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .el-tabs {
        flex: 1;
      }
    }
    
    .medicine-table {
      flex: 1;
      overflow-y: auto;
      margin-bottom: 20px;
    }
    
    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 20px;
      padding: 20px 0;
      margin-top: auto;
    }
  }
  
  .dialog-search {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;
  }
  
  .margin-right {
    margin-right: 15px;
  }
  
  .margin-top {
    margin-top: 20px;
  }
  
  .text-right {
    text-align: right;
  }
  
}

</style>